package com.ac.cron;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import com.ac.model.Cron;

import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import lombok.AllArgsConstructor;

@Component
@AllArgsConstructor
@SuppressWarnings({ "rawtypes", "unchecked" })
public class CronManager {

	private static CronManager manger;

	final MongoTemplate mongo;

	@PostConstruct
	public void init() {
		manger = this;
	}

	public static void run() {
		if (CronUtil.getScheduler().isStarted()) {
			CronUtil.getScheduler().stop(true);
		}

		isStatus = false;
		List<Cron> findAll = CronManager.manger.mongo.findAll(Cron.class);
		for (Cron cronDoc : findAll) {
			boolean status = cronDoc.isStatus();
			if (status)
				runTask(cronDoc);
		}

		if (isStatus) {
			// 支持秒级别定时任务
			CronUtil.setMatchSecond(true);
			CronUtil.start();
		}

//		runTask(new Document("cron","*/2 * * * * *")
//				.append("funStr", "com.ac.cron.task.TaskGet#task1"));

	}

	public static boolean isStatus = false;// 是否有任务需要执行

	/**
	 * 执行任务
	 */
	public static void runTask(Cron cronC) {
		isStatus = true;
		String cron = cronC.getCron();
		String funStr = cronC.getFunStr();
		String[] split = funStr.split("#");
		CronUtil.schedule(cron, new Task() {
			@Override
			public void execute() {
				try {
					Class t = Class.forName(split[0]);
					t.getMethod(split[1]).invoke(t);
				} catch (Exception e) {
				}
			}
		});
	}
}
